#!coding=utf-8
from django.shortcuts import *
from django.views.decorators.csrf import csrf_exempt
from django.db import transaction

import simplejson
from models import *
from map_data.models import *

def productMap(request):
	_enterPrise = request.session.get('ep',None)

	if not _enterPrise:
		result = {'error':'当前用户信息错误'}
		return HttpResponse(simplejson.dumps(result))

	_points,_centerPoint,_extent = _enterPrise.getGeoData()

	if not _points and not _centerPoint and not _extent:
		_points,_centerPoint,_extent = '[]','[]','[]'

	_listLen = len(ProductArea.objects.filter( enterprise = _enterPrise ))

	if _listLen % 10 == 0 :
		_maxPage = _listLen / 10
	else:
		_maxPage = _listLen / 10 + 1

	_tmpData = {}
	_tmpData['title'] = '生产区'
	_tmpData['addURL'] = '/facilities/productAreaAdd/'
	_tmpData['listURL'] = '/facilities/productAreaList/'
	_tmpData['key'] = 'production'
	_tmpData['mapDataURL'] = '/facilities/productAreaGeo/'
	_tmpData['dataURL'] = '/facilities/productAreaGeo/size/10/page/1/'
	_tmpData['dataPageURL'] = '/facilities/productAreaGeo/size/10/page/'
	_tmpData['dataSubmitURL'] = '/facilities/productAreaGeo/add/'
	_tmpData['dataStructure'] = 'id,name,desc'
	_tmpData['menuIndex'] = 0
	_tmpData['maxPage'] = _maxPage
	_tmpData['pagelist'] = range( 1 , _maxPage + 1)
	_tmpData['geo_points'] = _points
	_tmpData['geo_extent'] = _extent


	return render_to_response('enterprise/map/showMap.html', _tmpData, context_instance=RequestContext(request))

def productGeoDataList(request):
	_enterPrise = request.session.get('ep',None)

	if not _enterPrise:
		result = {'error':'当前用户信息错误'}
		return HttpResponse(simplejson.dumps(result))

	_mdc = MapDataCategory.objects.filter(name = '生产区')

	if len(_mdc) <= 0:
		result = {'error':'在地图数据分类中未查找到生产区分类'}
		return HttpResponse(simplejson.dumps(result))
	else:
		_mdc = _mdc[0]

	_md = MapData.objects.filter(mapData_type = _mdc, enterprise_id = _enterPrise.id)

	_groupStore = []

	for i in xrange(len(_md)):
		item = {}
		item['group'] = _md[i].getObj()    #mapdata
		item['data'] = []           #mapdata - - storage
		item['structure'] = 'id,name,desc'
		item['header'] = '编号,名称,描述'
		item['title'] = '生产区'
		_s = ProductArea.objects.filter(mapdata = _md[i], enterprise = _enterPrise.id )

		for j in xrange(len(_s)):
			item['data'].append( _s[j].getObj() )

			_groupStore.append( item ) 

	return HttpResponse( simplejson.dumps(_groupStore) )

def productDataByPage(request,pageSize,page):
	_enterPrise = request.session.get('ep',None)

	if not _enterPrise:
		result = {'error':'当前用户信息错误'}
		return HttpResponse(simplejson.dumps(result))

	pageSize = int(pageSize)
	page = int(page)

	_list = ProductArea.objects.filter(enterprise = _enterPrise)

	_listLen = len(_list)

	if _listLen % 10 == 0 :
		_maxPage = _listLen / 10
	else:
		_maxPage = _listLen / 10 + 1

	if page <= 0:
		page = 1

	if page > _maxPage:
		page = _maxPage

	_startNumber = (page - 1) * pageSize
	_endNumber = _startNumber + pageSize

	if _endNumber >= _listLen:
		_endNumber = _listLen

	_pageData = _list[_startNumber:_endNumber]

	_result = []

	for i in xrange(len(_pageData)):
		_result.append( _pageData[i].getObj() )

	return HttpResponse(simplejson.dumps(_result))

@csrf_exempt
@transaction.commit_on_success
def productGeoDataAdd(request):
    _enterPrise = request.session.get('ep',None)

    if not _enterPrise:
        result = {'error':'当前用户信息错误'}
        return HttpResponse(simplejson.dumps(result))

    _form = request.POST

    try:
        _mdc = MapDataCategory.objects.filter(name = '生产区')

        if len(_mdc) > 0:
            _mdc = _mdc[0]
        else:
            _mdc = MapDataCategory(name = '生产区',key = 'production')
            _mdc.save()

        _points = _form.get('points',None)
        center_point = _form.get('center',None)

        if not _points:
            result = {'error':'未选择地图'}
            return HttpResponse(simplejson.dumps(result))

        _m = MapData(points = _points, mapData_type = _mdc,enterprise_id = _enterPrise.id,center_point = center_point )
        _m.save()
        _ids = _form.get('ids',None)
        _ids = eval(_ids)
        _len = len(_ids)
        if _len <= 0 :
            result = {'error':'未选择存储单元'}
            return HttpResponse(simplejson.dumps(result))

        for i in xrange(_len):
            _id = int(_ids[i])
            _s = ProductArea.objects.get(id = _id)
            _s.mapdata = _m
            _s.save()
    except Exception,e:
        transaction.rollback()
        result = {'error':e.message if '' else (e.__str__()) }
        return HttpResponse(simplejson.dumps(result))
    else:
        result = {'success':'数据添加成功!'}
        return HttpResponse(simplejson.dumps(result))


def storageMap(request):
	_enterPrise = request.session.get('ep',None)

	if not _enterPrise:
		result = {'error':'当前用户信息错误'}
		return HttpResponse(simplejson.dumps(result))

	_points,_centerPoint,_extent = _enterPrise.getGeoData()

	if not _points and not _centerPoint and not _extent:
		_points,_centerPoint,_extent = '[]','[]','[]'

	_listLen = len(StorageArea.objects.filter( enterprise = _enterPrise ))

	if _listLen % 10 == 0 :
		_maxPage = _listLen / 10
	else:
		_maxPage = _listLen / 10 + 1

	_tmpData = {}
	_tmpData['title'] = '贮罐区'
	_tmpData['addURL'] = '/facilities/storageAreaAdd/'
	_tmpData['listURL'] = '/facilities/storageAreaList/'
	_tmpData['key'] = 'storage'
	_tmpData['mapDataURL'] = '/facilities/storageAreaGeo/'
	_tmpData['dataURL'] = '/facilities/storageAreaGeo/size/10/page/1/'
	_tmpData['dataPageURL'] = '/facilities/storageAreaGeo/size/10/page/'
	_tmpData['dataSubmitURL'] = '/facilities/storageAreaGeo/add/'
	_tmpData['dataStructure'] = 'id,name,desc'
	_tmpData['menuIndex'] = 1
	_tmpData['maxPage'] = _maxPage
	_tmpData['pagelist'] = range( 1 , _maxPage + 1)
	_tmpData['geo_points'] = _points
	_tmpData['geo_extent'] = _extent
	
	return render_to_response('enterprise/map/showMap.html', _tmpData, context_instance=RequestContext(request))

def storageGeoDataList(request):
	_enterPrise = request.session.get('ep',None)

	if not _enterPrise:
		result = {'error':'当前用户信息错误'}
		return HttpResponse(simplejson.dumps(result))

	_mdc = MapDataCategory.objects.filter(name = '贮罐区')

	if len(_mdc) <= 0:
		result = {'error':'在地图数据分类中未查找到贮罐区分类'}
		return HttpResponse(simplejson.dumps(result))
	else:
		_mdc = _mdc[0]

	_md = MapData.objects.filter(mapData_type = _mdc, enterprise_id = _enterPrise.id)

	_groupStore = []

	for i in xrange(len(_md)):
		item = {}
		item['group'] = _md[i].getObj()    #mapdata
		item['data'] = []           #mapdata - - storage
		item['structure'] = 'id,name,desc'
		item['header'] = '编号,名称,描述'
		item['title'] = '贮罐区'
		_s = StorageArea.objects.filter(mapdata = _md[i], enterprise = _enterPrise.id )

		for j in xrange(len(_s)):
			item['data'].append( _s[j].getObj() )

			_groupStore.append( item ) 

	return HttpResponse( simplejson.dumps(_groupStore) )

def storageDataByPage(request,pageSize,page):
	_enterPrise = request.session.get('ep',None)

	if not _enterPrise:
		result = {'error':'当前用户信息错误'}
		return HttpResponse(simplejson.dumps(result))

	pageSize = int(pageSize)
	page = int(page)

	_list = StorageArea.objects.filter(enterprise = _enterPrise)

	_listLen = len(_list)

	if _listLen % 10 == 0 :
		_maxPage = _listLen / 10
	else:
		_maxPage = _listLen / 10 + 1

	if page <= 0:
		page = 1

	if page > _maxPage:
		page = _maxPage

	_startNumber = (page - 1) * pageSize
	_endNumber = _startNumber + pageSize

	if _endNumber >= _listLen:
		_endNumber = _listLen

	_pageData = _list[_startNumber:_endNumber]

	_result = []

	for i in xrange(len(_pageData)):
		_result.append( _pageData[i].getObj() )

	return HttpResponse(simplejson.dumps(_result))

@csrf_exempt
@transaction.commit_on_success
def storageGeoDataAdd(request):
    _enterPrise = request.session.get('ep',None)

    if not _enterPrise:
        result = {'error':'当前用户信息错误'}
        return HttpResponse(simplejson.dumps(result))

    _form = request.POST

    try:
        _mdc = MapDataCategory.objects.filter(name = '贮罐区')

        if len(_mdc) > 0:
            _mdc = _mdc[0]
        else:
            _mdc = MapDataCategory(name = '贮罐区',key = 'storage')
            _mdc.save()

        _points = _form.get('points',None)
        center_point = _form.get('center',None)

        if not _points:
            result = {'error':'未选择地图'}
            return HttpResponse(simplejson.dumps(result))

        _m = MapData(points = _points, mapData_type = _mdc,enterprise_id = _enterPrise.id,center_point = center_point )
        _m.save()
        _ids = _form.get('ids',None)
        _ids = eval(_ids)
        _len = len(_ids)
        if _len <= 0 :
            result = {'error':'未选择存储单元'}
            return HttpResponse(simplejson.dumps(result))

        for i in xrange(_len):
            _id = int(_ids[i])
            _s = StorageArea.objects.get(id = _id)
            _s.mapdata = _m
            _s.save()
    except Exception,e:
        transaction.rollback()
        result = {'error':e.message if '' else (e.__str__()) }
        return HttpResponse(simplejson.dumps(result))
    else:
        result = {'success':'数据添加成功!'}
        return HttpResponse(simplejson.dumps(result))
